package com.reflection.cglib.dynamicmethod;

import java.lang.reflect.Method;

import org.objectweb.asm.Type;

import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InterfaceMaker;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibMethod {
	public static void main(String[] args) {
		InterfaceMaker interfaceMaker = new InterfaceMaker(); 
		interfaceMaker.add(new Signature("dynamicMethod", Type.getType(String.class), new Type[]{Type.getType(String.class)}), new Type[]{Type.getType(Exception.class)});
		
		
		Enhancer enhancer = new Enhancer();  
		enhancer.setSuperclass(MyClass.class); 
		enhancer.setInterfaces(new Class[]{interfaceMaker.create()});  
		enhancer.setCallback(new MethodInterceptor() {
			/**
			 * 第一个参数为代理对象
			 */
			@Override
			public Object intercept(Object obj, Method method, Object[] args,MethodProxy proxy) throws Throwable {
				if(method.getName().equals("dynamicMethod") && args != null && args[0] instanceof String){
					return "这是动态添加的方法" + args[0];
				}
				return proxy.invokeSuper(obj, args);
			}
		});
		
		
		MyClass myClass = (MyClass) enhancer.create();  
		try{
			 Method method = myClass.getClass().getMethod("dynamicMethod", new Class[] {String.class});  
			 String result = (String)method.invoke(myClass, ",这是参数");
			 System.out.println(result);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		myClass.myRealMethod();
	}
}
